﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.iBeacon
{
    /// <summary>回傳指定Region的地圖</summary>

    public class get_map : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";
            string MapPath = ChrisKit.RootDir + "CCPSIP\\iBeaconMap\\";

            try
            {
                //【01】取得POST參數
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string MapName = req.Form["MapName"];

                //【02】驗證使用者身分
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                    throw new Exception("ERROR_01: Cannot identify this device."); //無法識別此裝置

                //【03】驗證map是否存在資料庫中
                if (!iBeaconKit.IsMapExist(MapName))
                    throw new Exception("ERROR_02: Map does not exist."); //此map不存在資料庫中

                //【04】驗證map檔案是否存在iOS server中
                if (!(File.Exists(MapPath + MapName)))
                    throw new Exception("ERROR_02: Map does not exist."); //此map不存在iOS server中

                //【99】回傳Map檔案
                context.Response.ContentType = "application/octet-stream";
                context.Response.Charset = null;
                context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + MapName);
                context.Response.TransmitFile(MapPath + MapName);
                context.Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                //【99】回傳Xml
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
                context.Response.Charset = null;
                context.Response.Write(resultStr);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}